import { defineStore } from 'pinia'

/**
 * 用户状态管理
 * 包含用户信息、登录状态、钱包余额等
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: {
      id: '10086198',
      nickname: '蓝天飞行家',
      avatar: 'https://pan.feiwow.com/raw/files/2401749240120_.pic-1749240131553.jpg',
      level: 5,
      tags: ['低空旅游爱好者', '资深投资']
    },
    // 登录状态
    isLoggedIn: true,
    // 钱包信息
    wallet: {
      balance: 1280.50,
      coins: 2240.00,
      energy: 132.96
    },
    // 社交数据
    social: {
      following: 28,
      followers: 156,
      likes: 42,
      favorites: 8
    },
    // 身份等级信息
    identity: {
      name: '合伙人',
      level: 5,
      currentPoints: 1500,
      nextLevelPoints: 2000,
      benefits: [
        '基础建设值1.6倍',
        '每月获赠50积分',
        '专属客服通道'
      ]
    }
  }),
  
  getters: {
    // 获取用户头像
    userAvatar: (state) => state.userInfo.avatar,
    
    // 获取用户昵称
    userNickname: (state) => state.userInfo.nickname,
    
    // 获取用户等级
    userLevel: (state) => state.userInfo.level,
    
    // 获取钱包余额
    walletBalance: (state) => state.wallet.balance,
    
    // 获取升级进度百分比
    levelProgress: (state) => {
      return (state.identity.currentPoints / state.identity.nextLevelPoints) * 100
    }
  },
  
  actions: {
    /**
     * 更新用户信息
     * @param {Object} userInfo - 用户信息对象
     */
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },
    
    /**
     * 更新钱包余额
     * @param {Number} amount - 变动金额
     * @param {String} type - 变动类型：'balance'|'coins'|'energy'
     */
    updateWallet(amount, type = 'balance') {
      if (this.wallet[type] !== undefined) {
        this.wallet[type] += amount
      }
    },
    
    /**
     * 用户登录
     * @param {Object} credentials - 登录凭证
     * @returns {Promise} - 登录结果
     */
    async login(credentials) {
      try {
        // 这里应该调用API进行登录
        // const response = await api.user.login(credentials)
        
        // 模拟登录成功
        this.isLoggedIn = true
        return { success: true }
      } catch (error) {
        return { success: false, error }
      }
    },
    
    /**
     * 用户登出
     * @returns {Promise} - 登出结果
     */
    async logout() {
      try {
        // 这里应该调用API进行登出
        // await api.user.logout()
        
        // 清除用户状态
        this.isLoggedIn = false
        return { success: true }
      } catch (error) {
        return { success: false, error }
      }
    },
    
    /**
     * 增加电能
     * @param {Number} amount - 增加的电能数量
     */
    addEnergy(amount) {
      this.wallet.energy += amount
    }
  }
})